package com.ytjj.qmyx.mall.utils;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.ProductStatisticsDto;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.ProductStatisticsRequest;
import com.ytjj.qmyx.mall.model.response.ProductBroweRecordResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description 商品浏览记录工具类
 * @ClassName ProductRecordUtil
 *
 *
 * @Version 1.0
 **/

@Slf4j
@Component
public class ProductRecordUtil {
    @Resource
    private ProductBrowsingRecordMapper productBrowsingRecordMapper;
    @Resource
    private ProductMatchingMapper productMatchingMapper;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private ProductDao productDao;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductActivityMatchingMapper productActivityMatchingMapper;
    Executor pools = new ThreadPoolExecutor(5, 10, 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void productRecord(ProductBroweRecordResponse productBroweRecordResponse)  {

        String bankerName = "";
        // bankerName
        if(productBroweRecordResponse.getBankerId() != null) {
            Banker banker = bankerMapper.selectByPrimaryKey(productBroweRecordResponse.getBankerId());
            bankerName = banker.getName();
        }
        // 根据productId查询productMatching表信息
        ProductMatchingExample productMatchingExample = new ProductMatchingExample();
        productMatchingExample.createCriteria()
                .andProductIdEqualTo(productBroweRecordResponse.getProductId());
        List<ProductMatching> productMatchingList = productMatchingMapper.selectByExampleWithBLOBs(productMatchingExample);
        if(!CollectionUtils.isEmpty(productMatchingList)) {
            ProductMatching productMatching = productMatchingList.get(0);
            ProductBrowsingRecord productRecord = new ProductBrowsingRecord();
            productRecord.setSex(productMatching.getSex());
            productRecord.setProductId(productBroweRecordResponse.getProductId());
            productRecord.setComsumerPower(productMatching.getComsumerPower());
            productRecord.setAgeRange(productMatching.getAgeStr());
            productRecord.setProvinceJson(productMatching.getProvinceJson());
            productRecord.setLabelJson(productMatching.getLabelJson());
            productRecord.setBankerId(productBroweRecordResponse.getBankerId());
            productRecord.setBankerName(bankerName);
            productRecord.setProductName(productBroweRecordResponse.getProductName());
            productRecord.setActivityType(productBroweRecordResponse.getActivityType());
            productRecord.setActivityId(productBroweRecordResponse.getActivityId());
            productRecord.setColumnId(productBroweRecordResponse.getColumnId());
            productRecord.setCategoryId(productBroweRecordResponse.getCategoryId());
            productRecord.setUserId(productBroweRecordResponse.getUserId());
            productRecord.setIp(IPUtil.getIpAddress(TokenUtil.getRequest()));
            productRecord.setActivityFlag(Strings.isNotEmpty(productBroweRecordResponse.getActivityType()) ? (byte) 1 : (byte) 0);
            productRecord.setUuid(TokenUtil.getRequest().getHeader("uuid"));
            productRecord.setChannel(TokenUtil.getRequest().getHeader("channel"));
            productRecord.setModular(productBroweRecordResponse.getModular());
            productRecord.setH5Token(productBroweRecordResponse.getH5Token());
            productRecord.setCreateTime(new Date());
            productBrowsingRecordMapper.insertSelective(productRecord);
        }
    }

    /**
     * 浏览记录
     * @param productStatisticsRequest
     */
    public void browsingHistory(ProductStatisticsRequest productStatisticsRequest)  {

        ProductMatchingExample productMatchingExample = new ProductMatchingExample();
        productMatchingExample.createCriteria()
                .andProductIdEqualTo(productStatisticsRequest.getProductId());
        List<ProductMatching> productMatchingList = productMatchingMapper.selectByExample(productMatchingExample);
        ProductStatisticsDto productStatisticsDto = new ProductStatisticsDto();
        if(!CollectionUtils.isEmpty(productMatchingList)){
            ProductMatching productMatching = productMatchingList.get(0);
            productStatisticsDto.setSex(productMatching.getSex());
            productStatisticsDto.setAgeRange(productMatching.getAgeStr());
            productStatisticsDto.setProvinceJson(productMatching.getProvinceJson());
            productStatisticsDto.setLabelJson(productMatching.getLabelJson());
        }
        HttpServletRequest request = TokenUtil.getRequest();
        productStatisticsDto.setUuid(request.getHeader("uuid"));
        productStatisticsDto.setPlatform(TokenUtil.getSource());
        productStatisticsDto.setIp(IPUtil.getIpAddress(request));
        productStatisticsDto.setChannel(TokenUtil.getChannel());
        productStatisticsDto.setActivityType(productStatisticsRequest.getActivityType());
        productStatisticsDto.setIsActivity(productStatisticsRequest.getIsActivity());
        productStatisticsDto.setProductId(productStatisticsRequest.getProductId());
        productStatisticsDto.setProductName(productStatisticsRequest.getProductName());
        productStatisticsDto.setBankerId(productStatisticsRequest.getBankerId());
        productStatisticsDto.setCreateTime(new Date());
        productStatisticsDto.setScene(productStatisticsRequest.getScene());
        productStatisticsDto.setAccount(productStatisticsRequest.getAccount());
        try {
//            log.info("商品详情发送，商品统计消息：{}", JSONObject.toJSON(productStatisticsDto));
            pools.execute(() -> {
                rabbitTemplate.convertAndSend(QueueConstants.PRODUCT_STATISTICS_QUEUE,productStatisticsDto);
            });
        } catch (Exception e) {
            log.error("==={}", e);
        }
    }

    /**
     * 创建订单的商品轨迹记录
     *
     * @param productId
     */
    public void orderRecord(Integer productId ,Integer userId) {
//        ProductBroweRecordResponse productBroweRecordResponse = new ProductBroweRecordResponse();
//        productBroweRecordResponse.setUserId(userId);
//        Product product = productDao.getProductById(productId);
//        BeanUtils.copyProperties(product, productBroweRecordResponse);
//        productBroweRecordResponse.setProductId(product.getId());
//        this.productRecord(productBroweRecordResponse);

    }


}
